package com.fengyi.library.controller;

import com.fengyi.library.model.Loan;
import com.fengyi.library.model.User;
import com.fengyi.library.service.BookService;
import com.fengyi.library.service.LoanService;
import com.fengyi.library.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

/**
 * 首页控制器
 */
@Controller
public class HomeController {

    private final BookService bookService;
    private final UserService userService;
    private final LoanService loanService;

    @Autowired
    public HomeController(BookService bookService, UserService userService, LoanService loanService) {
        this.bookService = bookService;
        this.userService = userService;
        this.loanService = loanService;
    }

    /**
     * 访问首页
     */
    @GetMapping("/")
    public String home() {
        return "home";
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/dashboard")
    public String dashboard(Model model) {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User currentUser = null;
        if (authentication != null && authentication.isAuthenticated() && !authentication.getName().equals("anonymousUser")) {
            currentUser = userService.findByUsername(authentication.getName());
        }
        
        // 图书总数
        long bookCount = bookService.countBooks();
        model.addAttribute("bookCount", bookCount);
        
        // 用户总数
        long userCount = userService.findAllUsers().size();
        model.addAttribute("userCount", userCount);
        
        // 当前借阅总数
        long activeLoansCount = 0;
        // 逾期借阅总数
        long overdueLoansCount = loanService.findOverdueLoans().size();
        model.addAttribute("overdueLoansCount", overdueLoansCount);
        
        // 最新图书
        model.addAttribute("latestBooks", bookService.findAllBooks(
                PageRequest.of(0, 4, Sort.by(Sort.Direction.DESC, "createdAt"))
        ).getContent());
        
        // 最近借阅
        List<Loan> recentLoans;
        if (currentUser != null && currentUser.getRole().getName().equals("ROLE_ADMIN")) {
            // 管理员看所有最近借阅
            recentLoans = loanService.findAllLoans(
                    PageRequest.of(0, 5, Sort.by(Sort.Direction.DESC, "borrowDate"))
            ).getContent();
            // 更新活跃借阅总数
            activeLoansCount = loanService.findAllLoans(
                    PageRequest.of(0, Integer.MAX_VALUE)).getTotalElements();
        } else if (currentUser != null) {
            // 普通用户只看自己的借阅
            recentLoans = loanService.findLoansByUser(
                    currentUser, 
                    PageRequest.of(0, 5, Sort.by(Sort.Direction.DESC, "borrowDate"))
            ).getContent();
            // 更新当前用户的活跃借阅数
            activeLoansCount = loanService.countCurrentBorrowedBooks(currentUser);
        } else {
            recentLoans = List.of(); // 未登录用户看不到借阅
        }
        
        model.addAttribute("activeLoansCount", activeLoansCount);
        model.addAttribute("recentLoans", recentLoans);
        
        return "dashboard";
    }

    /**
     * 负载均衡测试页面
     */
    @GetMapping("/load-balancer-test")
    public String loadBalancerTest() {
        return "load-balancer-test";
    }
}
